package org.aptu.sd;

import org.aptu.sd.operationprovider.ICreditProvider;
import org.aptu.sd.operationprovider.IDebitProvider;
import org.aptu.sd.operationprovider.OperationFailedException;
import org.aptu.sd.model.Amount;
import org.aptu.sd.model.Currency;

/**
 * Created by IntelliJ IDEA.
 * User: andrey
 * Date: 12/7/11, 10:16 AM
 */
public class P2P implements IP2P {
    public static final int FEE_PERCENT = 2;
    private IDebitProvider debitProvider;
    private ICreditProvider creditProvider;

    public P2P(IDebitProvider debitProvider, ICreditProvider creditProvider) {
        this.debitProvider = debitProvider;
        this.creditProvider = creditProvider;
    }

    public void doP2P(String fromCard, String toCard, Amount amount, Currency currency) throws P2PFailedException {
        String debitRef;
        try {
            debitRef = debitProvider.debitCard(fromCard, amount, currency);
        } catch (OperationFailedException e) {
            throw new P2PFailedException("Debit operation failed", e);
        }

        Amount creditAmount = amount.subtractPercent(FEE_PERCENT);
        try {
            creditProvider.creditCard(toCard, creditAmount, currency);
        } catch (OperationFailedException e) {
            debitProvider.rollback(debitRef);
            throw new P2PFailedException("Credit operation failed", e);
        }
    }
}
